package com.inspur.edp.bef.bemanager.i18nservice;

import com.inspur.edp.bef.bizentity.GspBusinessEntity;
import com.inspur.edp.bef.bizentity.i18n.BizEntityResourceExtractor;
import com.inspur.edp.bef.bizentity.i18n.merge.BizEntityResourceMerger;
import com.inspur.edp.cef.designtime.api.i18n.context.CefResourceExtractContext;
import com.inspur.edp.cef.designtime.api.i18n.context.CefResourceMergeContext;
import com.inspur.edp.cef.designtime.api.i18n.merger.CefFieldResourceMerger;
import com.inspur.edp.lcm.metadata.api.entity.*;
import com.inspur.edp.lcm.metadata.spi.MetadataI18nService;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;

import java.util.List;

public class BizEntityI18nService implements MetadataI18nService {
    public GspMetadata merge(GspMetadata metadata, List<I18nResource> list) {
        if (list==null || list.size()==0)
            return metadata;
        if (!(metadata.getContent() instanceof GspBusinessEntity))
            return  metadata;
        I18nResourceItemCollection resourceItems=list.get(0).getStringResources();
        if (resourceItems==null)
            return metadata;
        GspBusinessEntity businessEntity= (GspBusinessEntity) metadata.getContent();
        mergeBizEntityResource(businessEntity,resourceItems);

        metadata.setContent(businessEntity);
        return metadata;
    }

    private void mergeBizEntityResource(GspBusinessEntity be,I18nResourceItemCollection resourceItems) {
        CefResourceMergeContext context=new CefResourceMergeContext(be.getDotnetGeneratingAssembly(),resourceItems);
        BizEntityResourceMerger merger=new BizEntityResourceMerger(be,context);
        merger.merge();
    }

    public I18nResource getResourceItem(GspMetadata metadata) {
        I18nResource resource = new I18nResource();
        resource.setResourceType(ResourceType.Metadata);
        resource.setResourceLocation(ResourceLocation.Backend);
        GspBusinessEntity be = (GspBusinessEntity) metadata.getContent();
        I18nResourceItemCollection collection = new I18nResourceItemCollection();
        ExtractBizEntityI18nResource(be, collection);

        resource.setStringResources(collection);
        return resource;
    }

    //region
    private void ExtractBizEntityI18nResource(GspBusinessEntity be, I18nResourceItemCollection items) {
        CefResourceExtractContext context = new CefResourceExtractContext(be.getDotnetGeneratingAssembly(), items);
        BizEntityResourceExtractor extractor = new BizEntityResourceExtractor(be, context);
        extractor.extract();
    }

    //endregion
}
